package com.uchengwang.ui.cm_ui.me.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SwitchCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.RyConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.IHttpManager;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.functions.http.manager.OSSManager;
import com.uchengwang.functions.image.ImageManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ActivityTitleBar;
import com.uchengwang.ui.base_ui.ui.AllBaseActivity;
import com.uchengwang.ui.cm_ui.login.ui.AuthenStateActivity;
import com.uchengwang.ui.cm_ui.ucity.listener.RxBusResultSubscriber;
import com.uchengwang.ui.utils.DialogUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.UCommonUtil;
import com.uchengwang.ui.view.CircleImageView;

import java.io.File;
import java.util.List;

import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;
import cn.finalteam.rxgalleryfinal.ui.RxGalleryListener;
import me.shaohui.advancedluban.OnCompressListener;


/**
 * Created by U城网 on 2017/6/30.
 * 创建群
 */

public class CreateGroupActivity extends AllBaseActivity implements View.OnClickListener{
    private ActivityTitleBar titleBa;
    private CircleImageView logo;
    private EditText groupName, dec;
    private SwitchCompat verify;
    private Button release;
    private TextView state, create_num;//使用说明
    private int type;//创建的群类型 不同群调用接口不一样 1好友群  2 U城交流群  3 校吧群 8社圈群
    private int orgType;//1兴趣圈 2老乡会 创建校吧交流群时用到

    private String headUrl, headUrlOss;//选择的图片地址 上传到oss的地址
    private String descS, groupNameS;
    private boolean isApproval = false;//加群是否需要验证
    private List<String> goingMembers;//上个界面带过来的选择用户 即将成为群成员-_-
    private String exchangeName;//创建交流群时, 群名称固定
    private int pubType;//创建U城活动群用到
    private long pubId, cycleId;//活动的ID/社圈id

    private boolean isAllow = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_create_group);
        type = getIntent().getIntExtra(BaseConfig.TYPE, -1);

        orgType = getIntent().getIntExtra(BaseConfig.ORG_TYPE, 0);

        exchangeName = getIntent().getStringExtra(BaseConfig.GROUP_NAME);
        goingMembers = getIntent().getStringArrayListExtra(BaseConfig.MEMBERS);
        pubType = getIntent().getIntExtra(BaseConfig.PUB_TYPE, -1);
        pubId = getIntent().getLongExtra(BaseConfig.PUB_ID, -1);
        cycleId = getIntent().getLongExtra(BaseConfig.ID, -1);

        
        initView();
    }
    
    private void initView(){
        titleBa = (ActivityTitleBar) findViewById(R.id.create_titleBa);
        logo = (CircleImageView) findViewById(R.id.create_logo);
        logo.setOnClickListener(this);
        groupName = (EditText) findViewById(R.id.create_groupName);
        dec = (EditText) findViewById(R.id.create_dec);
        verify = (SwitchCompat) findViewById(R.id.create_switch);
        release = (Button) findViewById(R.id.create_release);
        release.setOnClickListener(this);
        state = (TextView) findViewById(R.id.create_state);
        state.setOnClickListener(this);
        create_num = (TextView) findViewById(R.id.create_num);

        verify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                isApproval = b;
            }
        });

        titleBa.setTitle("创建群", 0);
        titleBa.setLeftListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                back();
            }
        });

        groupName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)){
                    create_num.setText("("+s.length()+"/15"+")");
                }else {
                    create_num.setText("(0/15)");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        switch (type){
            case 2:
                //交流群
                groupName.setText(exchangeName+"交流群");
                groupName.setFocusable(false);

                break;
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.create_logo:
                chooseImage();
                break;
            case R.id.create_release:
                if (UCommonUtil.getUtil().isNeedLogin(this, false)){
                    return;
                }
                groupNameS = groupName.getText().toString();
                descS = dec.getText().toString();
                if (TextUtils.isEmpty(groupNameS)){
                    UCommonUtil.getUtil().showToast(CreateGroupActivity.this, "请输入群名称");
                    return;
                }

                if (!isAllow){
                    return;
                }

                isAllow = false;

                LoadingUtils.getUtils().loading(this);
                if (TextUtils.isEmpty(headUrl)){
                    putInfo();
                }else {
                    compress();
                }

                break;
            case R.id.create_state://使用说明
                Intent intent = new Intent(this, AuthenStateActivity.class);
                intent.putExtra(BaseConfig.TYPE, 2);
                startActivity(intent);
                break;
        }
    }

    /**
     * 选择图片
     * */
    private void chooseImage(){
        UCommonUtil.getUtil().openGalleryMultiple(this, 1,new RxBusResultSubscriber<ImageMultipleResultEvent>() {
            @Override
            public void onEvent(ImageMultipleResultEvent event)  {
                //选择图片点击确定完成时的操作
                if (event != null && event.getResult() != null && event.getResult().size() >0){
                    headUrl = event.getResult().get(0).getThumbnailBigPath();

                    if (!TextUtils.isEmpty(headUrl)){
                        ImageManager.getInstance().loadImage(CreateGroupActivity.this, logo, new File(headUrl), ImageManager.ImageType.CIRCLE);
                    }
                }
            }
        },null, null);
    }

    /**
     * 压缩图片在上传
     * */
    private void compress(){
        UCommonUtil.getUtil().compressImageAlone(this, 300, headUrl, new OnCompressListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(File file) {
                String head = file.getAbsolutePath();//压缩后的想地址
                //上传到阿里云
                OSSManager.getOSSManager().putHeadToOss(head, new HttpCallBack() {
                    @Override
                    public void onError(int status, String msg) {
                        LoadingUtils.getUtils().hide();
                        isAllow = true;
                        UCommonUtil.getUtil().showToast(CreateGroupActivity.this, "图片上传失败");
                    }

                    @Override
                    public void onResp(int status, String msg, String data) {
                        //上传成功返回的oss的头像地址
                        headUrlOss = data;
                        putInfo();
                    }
                });
            }

            @Override
            public void onError(Throwable e) {
                LoadingUtils.getUtils().hide();
                UCommonUtil.getUtil().showToast(CreateGroupActivity.this, "图片选择错误");
                isAllow = true;
            }
        });
    }

    /**
     * 将信息提交到我们自己的服务器
     * */

    private void putInfo(){
        String url = "";

        MapRequest map = new MapRequest();
        map.put(BaseConfig.GROUP_NAME_UCW, groupNameS);
        map.put(BaseConfig.GROUP_DESC, descS);
        map.put(BaseConfig.IS_PUBLIC, true);
        map.put(BaseConfig.IS_NEED_APPLY, isApproval);

        //如果传过来的goingMembers 不为空 加人操作
        if (goingMembers != null && goingMembers.size() >0){
            int count = goingMembers.size();
            String[] mems = new String[count];
            for (int i=0;i <count; i++){
                mems[i] = goingMembers.get(i);
            }
            map.put(BaseConfig.USER_IDS, mems);
        }

        map.put(BaseConfig.USER_LIMIT, 500);
        if (TextUtils.isEmpty(headUrlOss)){
            map.put(BaseConfig.GROUP_LOGO, BaseConfig.SchoolBaLogo);
        }else {
            map.put(BaseConfig.GROUP_LOGO, headUrlOss);
        }
        map.put(BaseConfig.MEMBER_ROLE, BaseConfig.STUDENT_ROLE);

        if (UChengApplication.myUniId >0){
            map.put(BaseConfig.UNI_ID, UChengApplication.myUniId);
        }

        map.put(BaseConfig.CREATE_NICK_NAME, UChengApplication.nickName);
        map.put(BaseConfig.CREATE_UID, UCommonUtil.getUtil().getId());
        map.put(BaseConfig.ADMIN_NICK_NAME, UChengApplication.nickName);
        map.put(BaseConfig.ADMIN_UID, UCommonUtil.getUtil().getId());
        if (orgType > 0){
            map.put(BaseConfig.ORG_TYPE, orgType);
        }
        if (pubId >0){
            map.put(BaseConfig.ORG_ID, pubId);
            map.put(BaseConfig.REFER_ID, pubId);
        }

        if (cycleId >0){
            map.put(BaseConfig.REFER_ID, cycleId);
        }

        switch (type){
            case 3://校吧群
                switch (orgType){
                    case 1://1兴趣圈 2老乡会
                        url =  RyConfig.XQGroup.URL;
                        break;
                    case 2:
                        url =  RyConfig.LXGroup.URL;
                        break;
                }
                break;
            case 8://社圈群
                url = RyConfig.RCGROUP_GROUP_CYCLE;
                break;
        }

        HttpManager.newInstance(this).query(IHttpManager.RequestMethod.POST, url, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                Log.d("jjf", "status="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                isAllow = true;
                UCommonUtil.getUtil().showToast(CreateGroupActivity.this, "创建失败");
            }

            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("jjf", "status="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                isAllow = true;
                if (status ==0 ){
                    UCommonUtil.getUtil().showToast(CreateGroupActivity.this, "创建成功");
                    if (!TextUtils.isEmpty(data)){
                        BaseConfig.isRelease = true;
                        CreateGroupActivity.this.finish();
                    }
                    return;
                }
                UCommonUtil.getUtil().showToast(CreateGroupActivity.this, msg);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxGalleryListener.getInstance().setMultiImageCheckedListener(null);
    }

    @Override
    public void onBackPressed() {
        back();
    }

    private AlertDialog dialog;
    private void back(){
        if (!TextUtils.isEmpty(headUrl) || !TextUtils.isEmpty(groupName.getText().toString()) || !TextUtils.isEmpty(dec.getText().toString())){
            dialog = DialogUtils.getUtils().showDialogAll(this, false, "", "确定离开", "取消", "确定", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    CreateGroupActivity.this.finish();
                }
            }, null);
        }else {
            this.finish();
        }
    }
}
